import sys
import os
import commands


NOTIMP = "NOT implement."


class depBase(object):
    """dpoloyer base class.
    to deployer a software:

    cfdepoy list
    cfdeploy install xxx
    
    cfdeploy deploy --name=<> --scnarior=<>
    cfdeploy stop --name=<> --scnarior=<>
    
    cfdeploy fix  --name=<>
    cfdeploy monitor  --name=<>
    cfdeploy uninstall  --name=<>
    """

    def info(self):
        return self.__doc__

    def name(self):
        return self.__module__.split('_')[2].capitalize()

    def _run_cmd(self, cmd):
        status,output = commands.getstatusoutput(cmd)
        if status:
            raise Exception("run %s failed: %s"%(cmd,output))
        return output
    

    def _cmd_grep(self, cmd, str):
        output = self._run_cmd(cmd)
        outs = output.split('\n')
        for out in outs:
            if -1 != out.find(str):
                return out
        return None

    # setting: xxx
    def _cfg(self, file, option, value, sep=':'):
        cmd = r"""sudo sed -i 's/\(%s *%s *\).*/\1%s/' %s"""%(option, sep, value, file)
        print cmd
        self._run_cmd(cmd)

    # install/deploy/undeploy/showcfg
    def install(self, args):
        print "==========================="
        for pkg in self.PKGs:
            print "Installing", pkg
            status,output = commands.getstatusoutput("sudo apt-get install -y -f " + pkg)
            outs = output.split('\n')
            
            if status:
                for out in outs:
                    if -1 != out.find('Failed to fetch'):
                        print 'Error: please try to use official source.list'
                        raise Exception("install %s failed"%pkg)
                    if -1 != out.find('Could not get lock'):
                        print 'Error: remove the lock file.'
                        raise Exception("install %s failed"%pkg)
            else:
                print "Done"
        print "==========================="
        
    def uninstall(self, args):
        for pkg in self.rm_PKGs:
            os.system("sudo apt-get remove -y -f " + pkg)

    def showcfg(self, args):
        print "current cfg:", self.cfg.desc
        for name, value in self.cfg.items():
            if name != 'desc':
                print name,':', value

    def depoly(self, args):
        raise Exception(NOTIMP)
    
    def fix(self, args):
        raise Exception(NOTIMP)
    
    def check(self, args):
        raise Exception(NOTIMP)
